<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace app\admin\middleware;

use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

/**
 * Class StaticFile
 * @package app\middleware
 */
class CheckLogin implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $session    = $request->session();
        $path = $request->path();
        if (strpos($path, "/login/") === false) {

            // 用户未登录
            if (!$session->get('admin_id')) {
                // 拦截请求，返回一个重定向响应，请求停止向洋葱芯穿越
                return redirect('/admin/login/index');
            }

            if (!$this->checkAccessUrl($request)) {
                $request->validAccess = 'no';
                return response("对不起，你没有权限！");
            }
        }

        // 请求继续向洋葱芯穿越
        return $handler($request);
    }

    /**
     * 权限验证
     * @return [type] [description]
     */
    private function checkAccessUrl($request)
    {
        $url = $request->path();      
        $rt  = true;
        if (rtrim($url, '/') != $request->host()) {
            $menus = \app\admin\model\Access::where('ac_url', '<>', '')->column('ac_url', 'ac_id');
            foreach ($menus as $k => $v) {
                if (strpos($url, $v) !== false) {
                    $rt = checkAccess($k);
                    break;
                }
            }

        }
        return $rt;
    }
}
